<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 公共函数 v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

// 应用公共文件

include ROOT_PATH . 'application/constants.php';

/**
 * 请求是否为post或者ajax
 */
function is_submit() {
    $request = request();
    return $request->isPost() || $request->isAjax();
}

/**
 * 判断字符串是否以另一个字符串开头
 *
 * @param string $haystack 待判断的字符串
 * @param string $needle 开头字符串
 * @return bool
 */
function startsWith($haystack, $needle) {
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
}

/**
 * 判断字符串是否以另一个字符串结尾
 *
 * @param string $haystack 待判断的字符串
 * @param string $needle 结尾字符串
 * @return bool
 */
function endsWith($haystack, $needle) {
    return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}

/**
 * 获取数组中的某个属性值
 *
 * @param $arr
 * @param $field
 * @param $defaultVal
 * @param $returnDefaultValIfEmpty
 * @return mixed
 */
function fetch($arr, $field, $defaultVal = '', $returnDefaultValIfEmpty = false) {
    if (!is_array($arr)) {
        return $defaultVal;
    }
    if (!isset($arr[$field])) {
        return $defaultVal;
    }
    if ($returnDefaultValIfEmpty && empty($arr[$field])) {
        return $defaultVal;
    }
    return $arr[$field];
}

/**
 * 对数组元素进行重新映射
 *
 * @param $arr
 * @param $keyField
 * @return array
 */
function remap($arr, $keyField) {
    $newArr = [];
    $keys = [];
    foreach ($arr as $item) {
        $key = $item[$keyField];
        array_push($keys, $key);
        $newArr[$key] = $item;
    }

    return $newArr;
}